package org.jeecg.modules.purchaseList.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.zhyd.oauth.log.Log;
import org.apache.commons.lang.math.RandomUtils;
import org.jeecg.modules.buyer.entity.MtBuyer;
import org.jeecg.modules.buyer.service.IMtBuyerService;
import org.jeecg.modules.providers.entity.MtServiceProviders;
import org.jeecg.modules.providers.service.IMtServiceProvidersService;
import org.jeecg.modules.purchaseList.entity.MtPurchase;
import org.jeecg.modules.purchaseList.service.IMtPurchaseEquipService;
import org.jeecg.modules.purchaseList.vo.MtPurchasePage;
import org.jeecg.modules.station.entity.MtServiceStation;
import org.jeecg.modules.station.service.IMtServiceStationService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.purchaseList.entity.MtPurchaseEquip;
import org.jeecg.modules.purchaseList.service.IMtPurchaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 采购表单
 * @Author: jeecg-boot
 * @Date: 2023-12-12
 * @Version: V1.0
 */
@Api(tags = "采购表单")
@RestController
@RequestMapping("/purchaseList/mtPurchase")
@Slf4j
public class MtPurchaseController {
    @Autowired
    private IMtPurchaseService mtPurchaseService;
    @Autowired
    private IMtPurchaseEquipService mtPurchaseEquipService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IMtBuyerService buyerService;
    @Autowired
    private IMtServiceStationService stationService;
    @Autowired
    private IMtServiceProvidersService providersService;


    /**
     * 分页列表查询
     *
     * @param mtPurchase
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "采购表单-分页列表查询")
    @ApiOperation(value = "采购表单-分页列表查询", notes = "采购表单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MtPurchase>> queryPageList(MtPurchase mtPurchase,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        QueryWrapper<MtPurchase> queryWrapper = QueryGenerator.initQueryWrapper(mtPurchase, req.getParameterMap());
        LoginUser principal = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(principal.getId());
        //根据系统用户和表的关联，可以查处具体的采购人
        //MtBuyer buyer = buyerService.getOne(new LambdaQueryWrapper<MtBuyer>().eq(MtBuyer::getTel, sysUser.getTelephone()));
        //如果当前登录用户的角色是采购员，就只显示无需显示多余的东西，进货单
        queryWrapper.eq("invoices_type", "2");//采购类型是采购进货单的
        Page<MtPurchase> page = new Page<MtPurchase>(pageNo, pageSize);
        IPage<MtPurchase> pageList = mtPurchaseService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     *历史采购单
     */
    @ApiOperation(value = "采购表单-分页列表查询", notes = "采购表单-分页列表查询")
    @GetMapping(value = "/historyList")
    public Result<IPage<MtPurchase>> queryPageHistoryList(MtPurchase mtPurchase,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        QueryWrapper<MtPurchase> queryWrapper = QueryGenerator.initQueryWrapper(mtPurchase, req.getParameterMap());

        Page<MtPurchase> page = new Page<MtPurchase>(pageNo, pageSize);
        IPage<MtPurchase> pageList = mtPurchaseService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 采购进货列表
     */
    @ApiOperation(value = "采购进货表单-分页列表查询", notes = "采购进货表单-分页列表查询")
    @GetMapping(value = "/restockList")
    public Result<IPage<MtPurchase>> queryRestockPageList(MtPurchase mtPurchase,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        QueryWrapper<MtPurchase> queryWrapper = QueryGenerator.initQueryWrapper(mtPurchase, req.getParameterMap());
        LoginUser principal = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(principal.getId());
        //根据系统用户和表的关联，可以查处具体的采购人
        //MtBuyer buyer = buyerService.getOne(new LambdaQueryWrapper<MtBuyer>().eq(MtBuyer::getTel, sysUser.getTelephone()));
        //TODO 为了方便，先把采购员id定死，正常来写是buyer.getId
        //如果当前登录角色是采购员，就显示他的列表，已经审核过的
        /*if (sysUser.getUserType().equals(5)) {
            //根据系统用户和表的关联，可以查处具体的采购人
            //MtBuyer buyer = buyerService.getOne(new LambdaQueryWrapper<MtBuyer>().eq(MtBuyer::getTel, sysUser.getTelephone()));

            queryWrapper.eq("invoices_type", "3")//采购类型是采购进货单的
                    .eq("purchase_buyer_id", buyer.getId())
                    .eq("purchase_state", "1");//通过审核的
        }*/
        //如果登录角色是服务站，就显示该服务站所有的单子（已审核和未审核的）
        if (sysUser.getUserType().equals(2) || sysUser.getUserType().equals(1)) {
            queryWrapper.eq("invoices_type", "3");
        }
        Page<MtPurchase> page = new Page<>(pageNo, pageSize);
        IPage<MtPurchase> pageList = mtPurchaseService.page(page, queryWrapper);
        if (pageList.getSize() == 0) {
            return Result.OK("没有进货单");
        }
        return Result.OK(pageList);
    }

    /**
     * 采购退货单
     *
     * @param mtPurchase
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "采购退货表单-分页列表查询", notes = "采购退货表单-分页列表查询")
    @GetMapping(value = "/returnList")
    public Result<IPage<MtPurchase>> queryReturnPageList(MtPurchase mtPurchase,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                         HttpServletRequest req) {
        QueryWrapper<MtPurchase> queryWrapper = QueryGenerator.initQueryWrapper(mtPurchase, req.getParameterMap());
        LoginUser principal = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(principal.getId());

        //如果登录者是服务站角色 , 服务商角色
        if (sysUser.getUserType().equals(2) || sysUser.getUserType().equals(1)) {
            queryWrapper.eq("invoices_type", "4");
        }
        //如果登录者是采购员角色
        /*if (sysUser.getUserType().equals(5)) {
            //根据系统用户和表的关联，可以查处具体的采购人
            MtBuyer buyer = buyerService.getOne(new LambdaQueryWrapper<MtBuyer>().eq(MtBuyer::getTel, sysUser.getTelephone()));
            //TODO 为了方便，先把采购员id定死，正常来写是buyer.getId
            queryWrapper.eq("purchase_buyer_id", buyer.getId())
                    .eq("purchase_state", "1")//通过审核的
                    .eq("invoices_type", "4");//采购类型是采购退货单的
        }*/

        Page<MtPurchase> page = new Page<MtPurchase>(pageNo, pageSize);
        IPage<MtPurchase> pageList = mtPurchaseService.page(page, queryWrapper);
        if (pageList.getSize() == 0) {
            return Result.OK("没有退货单");
        }
        return Result.OK(pageList);
    }

    /**
     * 供应商结算单
     *
     * @param mtPurchase
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "供应商结算单-分页列表查询", notes = "供应商结算单-分页列表查询")
    @GetMapping(value = "/settleStatementList")
    public Result<IPage<MtPurchase>> querySettleStatementPageList(MtPurchase mtPurchase,
                                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                  HttpServletRequest req) {
        QueryWrapper<MtPurchase> queryWrapper = QueryGenerator.initQueryWrapper(mtPurchase, req.getParameterMap());
        LoginUser principal = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(principal.getId());
        //TODO 供应商结算单子的list操作
        //如果登录者是服务站角色 , 服务商角色
        if (sysUser.getUserType().equals(2) || sysUser.getUserType().equals(1)) {
            queryWrapper.eq("invoices_type", "5");
        }
        //如果登录者是采购员角色，
        // 可以设计成只能服务商或者服务站才能看到结算页面
        /*if (sysUser.getUserType().equals(5)) {
            //根据系统用户和表的关联，可以查处具体的采购人
            MtBuyer buyer = buyerService.getOne(new LambdaQueryWrapper<MtBuyer>().eq(MtBuyer::getTel, sysUser.getTelephone()));
            //TODO 为了方便，先把采购员id定死，正常来写是buyer.getId
            queryWrapper.eq("purchase_buyer_id", buyer.getId())
                    .eq("purchase_state", "1")//通过审核的
                    .eq("invoices_type", "5");//采购类型是供货商结算的
        }*/
        Page<MtPurchase> page = new Page<MtPurchase>(pageNo, pageSize);
        IPage<MtPurchase> pageList = mtPurchaseService.page(page, queryWrapper);
        if (pageList.getSize() == 0) {
            return Result.OK("没有退货单");
        }
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param mtPurchasePage
     * @return
     */
    @AutoLog(value = "采购表单-添加")
    @ApiOperation(value = "采购表单-添加", notes = "采购表单-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MtPurchasePage mtPurchasePage) {
        //判断，如果机构id和供应商id相同，就报错
        if (mtPurchasePage.getOrganizationId().equals(mtPurchasePage.getProviderId())) {
            return Result.error("机构和供应商不能是同一个");
        }
        //判断如果没有子表数据，就不能提交
        if (mtPurchasePage.getMtPurchaseEquipList().size()==0){
            return Result.error("没有设备数据，提交无效");
        }
        MtPurchase mtPurchase = new MtPurchase();
        BeanUtils.copyProperties(mtPurchasePage, mtPurchase);
        //设置当前登录人是采购员
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        if (sysUser.getUserType().equals(2)) {
            LambdaQueryWrapper<MtServiceStation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MtServiceStation::getUserId, sysUser.getUsername());
            MtServiceStation station = stationService.getOne(queryWrapper);
            mtPurchase.setPurchaseBuyerId(station.getId());
            mtPurchase.setPurchaseBuyerName(station.getStationName());

        }
        if (sysUser.getUserType().equals(1)) {
            LambdaQueryWrapper<MtServiceProviders> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MtServiceProviders::getUserId, sysUser.getUsername());
            MtServiceProviders providers = providersService.getOne(queryWrapper);
            mtPurchase.setPurchaseBuyerId(providers.getId());
            mtPurchase.setPurchaseBuyerName(providers.getProName());
        }
        mtPurchase.setPurchaseState("0");//设置单据是够审核，0未审核，1已审核
        mtPurchase.setInvoicesType("2");//设置单据的类型是2，采购单据

        List<MtPurchaseEquip> list = mtPurchasePage.getMtPurchaseEquipList();
        Integer num = 0;
        Double total = 0d;

        for (MtPurchaseEquip mtPurchaseEquip : list) {
            Integer number = mtPurchaseEquip.getNumber();
            num += number;
            Double equipPrice = mtPurchaseEquip.getEquipPrice();
            double equipTotal = equipPrice * number;
            mtPurchaseEquip.setLongleTotal(equipTotal);
            total += equipTotal;
        }
        mtPurchase.setEquipNum(num);//设置设备数量
        //设置总费用：
        mtPurchase.setTotalCost(total);
        mtPurchaseService.saveMain(mtPurchase, list);
        return Result.OK("添加成功！");
    }
    /**
     * @param mtPurchasePage
     * @return
     */
    @AutoLog(value = "采购进货表单-添加")
    @ApiOperation(value = "采购进货表单-添加", notes = "采购进货表单-添加")
    @PostMapping(value = "/addRestock")
    public Result<String> addRestock(@RequestBody MtPurchasePage mtPurchasePage) {
        MtPurchase mtPurchase = new MtPurchase();
        if (mtPurchasePage.getMtPurchaseEquipList().size() == 0 || mtPurchasePage.getMtPurchaseEquipList() == null) {
            return Result.error("没有选择设备，无法保存");
        }

        BeanUtils.copyProperties(mtPurchasePage, mtPurchase);
        mtPurchase.setInvoicesType("3");//设置单子类型 是进货单
        //mtPurchase.setReceiptId(mtPurchasePage.getReceiptId());//设置单子的单据号
        mtPurchase.setPurchaseState("0");//设置审核状态
        mtPurchase.setSettlementStatus("0");//设置结算状态
        //mtPurchase.setId("");//设置id为空
        //设置采购人是自己
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        if (sysUser.getUserType().equals(2)) {
            LambdaQueryWrapper<MtServiceStation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MtServiceStation::getUserId, sysUser.getUsername());
            MtServiceStation station = stationService.getOne(queryWrapper);
            mtPurchase.setPurchaseBuyerId(station.getId());
            mtPurchase.setPurchaseBuyerName(station.getStationName());
        }
        if (sysUser.getUserType().equals(1)) {
            LambdaQueryWrapper<MtServiceProviders> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MtServiceProviders::getUserId, sysUser.getUsername());
            MtServiceProviders providers = providersService.getOne(queryWrapper);
            mtPurchase.setPurchaseBuyerId(providers.getId());
            mtPurchase.setPurchaseBuyerName(providers.getProName());
        }
        List<MtPurchaseEquip> list = mtPurchasePage.getMtPurchaseEquipList();
        Integer num = 0;
        Double total = 0d;
        List<MtPurchaseEquip> equipList = new ArrayList<>();
        if (list.size() > 0) {
            for (MtPurchaseEquip mtPurchaseEquip : list) {
                Integer number = mtPurchaseEquip.getNumber();
                //计算总个数
                num += number;
                Double equipPrice = mtPurchaseEquip.getEquipPrice();
                double equipTotal = equipPrice * number;
                //设置单个设备的总价
                mtPurchaseEquip.setLongleTotal(equipTotal);
                //计算所有商品的总价
                total += equipTotal;
                //将id值赋值为空，为了后期插入操作方便
                mtPurchaseEquip.setId("");
                //设置创建时间
                mtPurchaseEquip.setCreateTime(new Date());
                equipList.add(mtPurchaseEquip);
            }
        }

        mtPurchase.setEquipNum(num);//设置设备数量
        //设置总费用：
        mtPurchase.setTotalCost(total);
        //设置穿件时间
        mtPurchase.setCreateTime(new Date());
        //新增一条记录
        mtPurchaseService.saveMain(mtPurchase, equipList);
        return Result.OK("添加成功！");
    }

    /**
     * 采购退货单
     */
    @AutoLog(value = "采购退货表单-添加")
    @ApiOperation(value = "采购退货表单-添加", notes = "采购退货表单-添加")
    @PostMapping(value = "/addReturn")
    public Result<String> addReturn(@RequestBody MtPurchasePage mtPurchasePage) {
        MtPurchase mtPurchase = new MtPurchase();
        //如果没有关联的id，就报错
        if (mtPurchasePage.getPurchaseRelId() == null || mtPurchasePage.getPurchaseRelId().equals("")) {
            return Result.error("必须指定一个进货单，才能进行退货");
        }

        //copy
        BeanUtils.copyProperties(mtPurchasePage, mtPurchase);

        //设置采购人是自己
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        if (sysUser.getUserType().equals(2)) {
            LambdaQueryWrapper<MtServiceStation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MtServiceStation::getUserId, sysUser.getUsername());
            MtServiceStation station = stationService.getOne(queryWrapper);
            mtPurchase.setPurchaseBuyerId(station.getId());
            mtPurchase.setPurchaseBuyerName(station.getStationName());
            mtPurchase.setOrganizationId(station.getId());
            mtPurchase.setOrganizationName(station.getStationName());
        }
        if (sysUser.getUserType().equals(1)) {
            LambdaQueryWrapper<MtServiceProviders> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MtServiceProviders::getUserId, sysUser.getUsername());
            MtServiceProviders providers = providersService.getOne(queryWrapper);
            mtPurchase.setPurchaseBuyerId(providers.getId());
            mtPurchase.setPurchaseBuyerName(providers.getProName());
            mtPurchase.setOrganizationName(providers.getProName());
            mtPurchase.setOrganizationId(providers.getId());
        }
        //如果传过来的是没有设置单子类型的，设置成为采购单，如果类型是2的，就设置成3，进货;，如果类型是3，就设置成4退货单
        mtPurchase.setInvoicesType("4");
        //mtPurchase.setReceiptId(mtPurchasePage.getReceiptId());//设置单据号
        mtPurchase.setSettlementStatus("0");//设置结算状态是0 未结算的状态
        mtPurchase.setPurchaseState("0");//设置审核状态
        List<MtPurchaseEquip> list = mtPurchasePage.getMtPurchaseEquipList();
        Integer num = 0;
        double total = 0d;
        List<MtPurchaseEquip> equipList = new ArrayList<>();
        if (list.size() > 0) {
            for (MtPurchaseEquip mtPurchaseEquip : list) {
                Integer number = mtPurchaseEquip.getNumber();
                num += number;
                Double equipPrice = mtPurchaseEquip.getEquipPrice();
                double equipTotal = equipPrice * number;
                //设置单个设备的总价
                mtPurchaseEquip.setLongleTotal(equipTotal);
                //计算所有设备的总价
                total += equipTotal;
                //设置关联的单子id
                mtPurchaseEquip.setId("");
                mtPurchaseEquip.setCreateTime(new Date());
                equipList.add(mtPurchaseEquip);
            }
        }
        mtPurchase.setEquipNum(num);//设置设备数量
        //设置总费用：
        mtPurchase.setTotalCost(total);
        //设置创建时间
        mtPurchase.setCreateTime(new Date());
        //新增一条记录
        mtPurchaseService.saveMain(mtPurchase, equipList);
        return Result.OK("添加成功！");

    }


    /**
     * 供应商结算单
     */
    @AutoLog(value = "供应商结算单-添加")
    @ApiOperation(value = "供应商结算单-添加", notes = "供应商结算单-添加")
    @PostMapping(value = "/addSettleStatement")
    public Result<String> addSettleStatement(@RequestBody MtPurchasePage mtPurchasePage) {
        List<MtPurchase> list = mtPurchasePage.getMtPurchaseList();
        if (list.size() == 0) {
            return Result.error("没有选择供应商的进退货单子");
        }
        MtPurchase mtPurchase = new MtPurchase();
        BeanUtils.copyProperties(mtPurchasePage, mtPurchase);
        //设置结算单的金额
        Double totalAll = 0d;
        //将传来的单子进行循环，进货是正的，退货是负的
        for (MtPurchase mt : list) {
            //如果是进货单，
            if (mt.getInvoicesType().equals("3")) {
                totalAll += mt.getTotalCost();
            }
            //如果是退货单
            if (mt.getInvoicesType().equals("4")) {
                totalAll -= mt.getTotalCost();
            }
            //选择好的供应商单子的结算状态修改成一结算就好了
            mt.setSettlementStatus("1");
        }
        //将计算好的结算单金额赋值
        mtPurchase.setTotalCost(totalAll);
        //如果传过来的是没有设置单子类型的，设置成为采购单，如果类型是2的，就设置成3，进货;，如果类型是3，就设置成4退货单,5是结算单
        mtPurchase.setInvoicesType("5");
        mtPurchase.setPurchaseState("0");//设置审核状态
        //将这条消息进行保存
        mtPurchaseService.save(mtPurchase);
        //根据结算单的单据号，查出结算单的详细信息
        LambdaQueryWrapper<MtPurchase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MtPurchase::getReceiptId, mtPurchase.getReceiptId());
        MtPurchase purchaseSettle = mtPurchaseService.getOne(queryWrapper);
        //数据库中药新增一个字段，记录已生成的结算单id，将list中的所有元素的关联的结算单id都写成刚生成的这个结算单id
        for (MtPurchase mtPurchase1 : list) {
            mtPurchase1.setSettlementId(purchaseSettle.getId());
            //保存修改好的内容
            mtPurchaseService.updateById(mtPurchase1);
        }
        return Result.OK("添加成功！");

    }


    /**
     * 编辑
     *
     * @param mtPurchasePage
     * @return
     */
    @AutoLog(value = "采购表单-编辑")
    @ApiOperation(value = "采购表单-编辑", notes = "采购表单-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MtPurchasePage mtPurchasePage) {
        MtPurchase mtPurchase = new MtPurchase();
        BeanUtils.copyProperties(mtPurchasePage, mtPurchase);
        MtPurchase mtPurchaseEntity = mtPurchaseService.getById(mtPurchase.getId());
        if (mtPurchaseEntity == null) {
            return Result.error("未找到对应数据");
        }
        mtPurchaseService.updateMain(mtPurchase, mtPurchasePage.getMtPurchaseEquipList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "采购表单-通过id删除")
    @ApiOperation(value = "采购表单-通过id删除", notes = "采购表单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        mtPurchaseService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "采购表单-批量删除")
    @ApiOperation(value = "采购表单-批量删除", notes = "采购表单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mtPurchaseService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "采购表单-通过id查询")
    @ApiOperation(value = "采购表单-通过id查询", notes = "采购表单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MtPurchase> queryById(@RequestParam(name = "id", required = true) String id) {
        MtPurchase mtPurchase = mtPurchaseService.getById(id);
        if (mtPurchase == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mtPurchase);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "采购的设备表通过主表ID查询")
    @ApiOperation(value = "采购的设备表主表ID查询", notes = "采购的设备表-通主表ID查询")
    @GetMapping(value = "/queryMtPurchaseEquipByMainId")
    public Result<List<MtPurchaseEquip>> queryMtPurchaseEquipListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<MtPurchaseEquip> mtPurchaseEquipList = mtPurchaseEquipService.selectByMainId(id);
        return Result.OK(mtPurchaseEquipList);
    }

    @GetMapping("/queryMtPurchaseBySettlementId")
    public Result<IPage<MtPurchase>> queryMtPurchaseBySettlementId(@RequestParam("id") String id) {
        LambdaQueryWrapper<MtPurchase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MtPurchase::getSettlementId, id);
        Page<MtPurchase> page = new Page<>(1, 10000);
        IPage<MtPurchase> pageList = mtPurchaseService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mtPurchase
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MtPurchase mtPurchase) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<MtPurchase> queryWrapper = QueryGenerator.initQueryWrapper(mtPurchase, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<MtPurchase> mtPurchaseList = mtPurchaseService.list(queryWrapper);

        // Step.3 组装pageList
        List<MtPurchasePage> pageList = new ArrayList<MtPurchasePage>();
        for (MtPurchase main : mtPurchaseList) {
            MtPurchasePage vo = new MtPurchasePage();
            BeanUtils.copyProperties(main, vo);
            List<MtPurchaseEquip> mtPurchaseEquipList = mtPurchaseEquipService.selectByMainId(main.getId());
            vo.setMtPurchaseEquipList(mtPurchaseEquipList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "采购表单列表");
        mv.addObject(NormalExcelConstants.CLASS, MtPurchasePage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("采购表单数据", "导出人:" + sysUser.getRealname(), "采购表单"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MtPurchasePage> list = ExcelImportUtil.importExcel(file.getInputStream(), MtPurchasePage.class, params);
                for (MtPurchasePage page : list) {
                    MtPurchase po = new MtPurchase();
                    BeanUtils.copyProperties(page, po);
                    mtPurchaseService.saveMain(po, page.getMtPurchaseEquipList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    //采购单子的编号自动生成
    @GetMapping("/oddNumber")
    public Result<MtPurchase> getOddNumber(@RequestParam("str") String str) {
        String qianzhui = "";
        //单据号的自动生成
        if (str.equals("1")) {
            qianzhui = "cg";
        }
        if (str.equals("2")) {
            qianzhui = "JH";
        }
        if (str.equals("3")) {
            qianzhui = "TH";
        }
        if (str.equals("4")) {
            qianzhui = "JS";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        int i = RandomUtils.nextInt(90) + 10;
        String format = simpleDateFormat.format(new Date());
        String res = qianzhui + format + i;
        MtPurchase mtPurchase = new MtPurchase();
        //设置单据号
        mtPurchase.setReceiptId(res);
        //当前登录用户的所属的服务站和服务商
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        //如果是服务站角色
        if (sysUser.getUserType().equals(2)) {
            LambdaQueryWrapper<MtServiceStation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MtServiceStation::getUserId, sysUser.getUsername());
            MtServiceStation station = stationService.getOne(queryWrapper);
            //设置 服务站 和服务商
            mtPurchase.setOrganizationId(station.getId());
            mtPurchase.setOrganizationName(station.getStationName());
            mtPurchase.setProviderId(station.getProviderId());
            mtPurchase.setPurchaseBuyerId(station.getId());
            mtPurchase.setPurchaseBuyerName(station.getStationName());
        }
        //如果是服务商角色
        if (sysUser.getUserType().equals(1)) {
            LambdaQueryWrapper<MtServiceProviders> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MtServiceProviders::getUserId, sysUser.getUsername());
            MtServiceProviders providers = providersService.getOne(queryWrapper);
            //设置 服务站
            mtPurchase.setOrganizationId(providers.getId());
            mtPurchase.setOrganizationName(providers.getProName());
            mtPurchase.setPurchaseBuyerId(providers.getId());
            mtPurchase.setPurchaseBuyerName(providers.getProName());
        }
        return Result.OK(mtPurchase);
    }
    //进货订单选择的采购单号码
    @PostMapping("/getRelOrderIds")
    public Result<List<String>> getRelOrderIds() {
        LambdaQueryWrapper<MtPurchase> queryWrapper = new LambdaQueryWrapper<>();
        //可选类型是订货单，并且通过审核的
        queryWrapper.eq(MtPurchase::getInvoicesType, "2")
                .eq(MtPurchase::getPurchaseState, "1");
        //当前登录者的机构
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        //如果当前登录者是服务商
        if (sysUser.getUserType().equals(1)){
            LambdaQueryWrapper<MtServiceProviders> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(MtServiceProviders::getUserId,sysUser.getUsername());
            MtServiceProviders providers = providersService.getOne(queryWrapper1);

            queryWrapper.eq(MtPurchase::getOrganizationId,providers.getId());
        }
        //如果登录者是服务站
        if (sysUser.getUserType().equals(2)){
            LambdaQueryWrapper<MtServiceStation> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(MtServiceStation::getUserId,sysUser.getUsername());
            MtServiceStation station = stationService.getOne(queryWrapper1);
            queryWrapper.eq(MtPurchase::getOrganizationId,station.getId());
        }
        List<MtPurchase> list = mtPurchaseService.list(queryWrapper);
        List<String> stringList = list.stream().map(MtPurchase::getReceiptId).collect(Collectors.toList());
        if (stringList.size() == 0) {
            return Result.error("没有采购单据");
        }
        return Result.ok(stringList);
    }

    //退货单可选择的进货单据号
    @GetMapping("/getRestockOrder")
    public Result<List<String>> getRestockOrder() {
        LambdaQueryWrapper<MtPurchase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MtPurchase::getInvoicesType, "3") //单据类型是进货单的
                .eq(MtPurchase::getPurchaseState,"1");//通过审核的
        //当前登录者的机构
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        //如果当前登录者是服务商
        if (sysUser.getUserType().equals(1)){
            LambdaQueryWrapper<MtServiceProviders> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(MtServiceProviders::getUserId,sysUser.getUsername());
            MtServiceProviders providers = providersService.getOne(queryWrapper1);
            queryWrapper.eq(MtPurchase::getOrganizationId,providers.getId());
        }
        //如果登录者是服务站
        if (sysUser.getUserType().equals(2)){
            LambdaQueryWrapper<MtServiceStation> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(MtServiceStation::getUserId,sysUser.getUsername());
            MtServiceStation station = stationService.getOne(queryWrapper1);
            queryWrapper.eq(MtPurchase::getOrganizationId,station.getId());
        }
        //所有的进货单据
        List<MtPurchase> listRestock = mtPurchaseService.list(queryWrapper);
        //排除那些已经是已经生成过退单的单据
        //查询现有的退订单的单据对象
        LambdaQueryWrapper<MtPurchase> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper.eq(MtPurchase::getInvoicesType, "4");
        //所有的进货单据
        List<MtPurchase> listReturn = mtPurchaseService.list(queryWrapper2);
        List<MtPurchase> list = new ArrayList<>();
        for (MtPurchase mtReturnPur : listReturn) {
            for (MtPurchase mtRestock : listRestock) {
                //如果进货单的id和退单的关联id相同，就说明是已经退过单了，不相等就说明没生成过退货单
                if (!mtRestock.getId().equals(mtReturnPur.getId())) {
                    list.add(mtRestock);
                }
            }
        }
        List<String> stringList = list.stream().map(MtPurchase::getReceiptId).collect(Collectors.toList());
        return Result.ok(stringList);
    }

    //选好单据号之后，根据单据号背后的id，查询该单子的子表数据
    @GetMapping("/getZiTable")
    public Result<MtPurchasePage> getEquipList(@RequestParam("orderId") String orderId) {
        LambdaQueryWrapper<MtPurchaseEquip> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MtPurchaseEquip::getMtPurchaseId, orderId);
        List<MtPurchaseEquip> list = mtPurchaseEquipService.list(queryWrapper);
        MtPurchase purchase = mtPurchaseService.getById(orderId);
        MtPurchasePage mtPurchasePage = new MtPurchasePage();
        BeanUtils.copyProperties(purchase, mtPurchasePage);
        mtPurchasePage.setMtPurchaseEquipList(list);
        return Result.ok(mtPurchasePage);
    }

    /**
     * 根据传过来的进货id，查出它的关联的采购信息
     */
    @GetMapping("/getCGId")
    public String getCGId(@RequestParam String JHid) {
        MtPurchase byId = mtPurchaseService.getById(JHid);
        return byId.getPurchaseRelId();
    }

    /**
     * 对采购的审核
     *
     * @param id
     * @return
     */
    @GetMapping("/audit")
    public Result<String> audit(@RequestParam("id") String id) {
        //根据id查询出该对象
        MtPurchase mtPurchase = mtPurchaseService.getById(id);
        //修改审核状态
        mtPurchase.setPurchaseState("1");
        //修改审核时间
        mtPurchase.setAuditTime(new Date());
        //保存已经修改过的数据
        boolean b = mtPurchaseService.updateById(mtPurchase);
        if (b) {
            return Result.OK("审核通过");
        } else {
            return Result.error("审核失败");
        }
    }

    /**
     * 给历史单据页面付初始值
     */
    @GetMapping("/getStation")
    public Result<MtPurchase> getStation() {
        MtPurchase mtPurchase = new MtPurchase();
        //根据当前登录用户查询所属的机构id
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(loginUser.getId());
        //如果是服务站角色
        if (sysUser.getUserType().equals(2)) {
            LambdaQueryWrapper<MtServiceStation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MtServiceStation::getUserId, sysUser.getUsername());

            MtServiceStation station = stationService.getOne(queryWrapper);
            mtPurchase.setOrganizationId(station.getId());
            mtPurchase.setOrganizationName(station.getStationName());
        }
        //如果是服务商角色
        if (sysUser.getUserType().equals(1)) {
            LambdaQueryWrapper<MtServiceProviders> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MtServiceProviders::getUserId, sysUser.getUsername());
            MtServiceProviders providers = providersService.getOne(queryWrapper);
            mtPurchase.setOrganizationName(providers.getProName());
            mtPurchase.setOrganizationId(providers.getId());
        }
        return Result.ok(mtPurchase);
    }

    /**
     * 结算单的选择数据（可选的进货单和退货单）
     * @param mtPurchase
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping("/getSettleStatement")
    public Result<IPage<MtPurchase>> getSettleStatement(MtPurchase mtPurchase,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        QueryWrapper<MtPurchase> queryWrapper = QueryGenerator.initQueryWrapper(mtPurchase, req.getParameterMap());
        LoginUser principal = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = sysUserService.getById(principal.getId());
        //如果当前登录用户是服务商
        if (sysUser.getUserType().equals(1)){
            LambdaQueryWrapper<MtServiceProviders> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(MtServiceProviders::getUserId,sysUser.getUsername());
            MtServiceProviders providers = providersService.getOne(queryWrapper1);

            queryWrapper.eq("organization_id",providers.getId());
        }
        //如果当前的鞥路用户是服务站
        if (sysUser.getUserType().equals(2)){
            LambdaQueryWrapper<MtServiceStation> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(MtServiceStation::getUserId,sysUser.getUsername());
            MtServiceStation station = stationService.getOne(queryWrapper1);
            queryWrapper.eq("organization_id",station.getId());//查询当当登录id，也就是机构id的数据
        }
        queryWrapper.eq("settlement_status", "0")//查询结算状态是“0”的数据（未结算）
                .eq("provider_id", mtPurchase.getProviderId())//查询专属供应商的单子数据
                .in("invoices_type", "3", "4");//查询单据状态是3 和4 的单子数据（进货单和退货单）

        Page<MtPurchase> page = new Page<MtPurchase>(pageNo, pageSize);
        IPage<MtPurchase> pageList = mtPurchaseService.page(page, queryWrapper);

        return Result.OK(pageList);
    }
}
